require '../db_help/db_help'
require 'taobao_api'
def get_taobaoke_detail(dao,nick,num_ids)
        begin
          rs = dao.query("select id from taoke_items where num_iid=#{num_ids}")
          result ={}
          if rs.num_rows>0
            row = rs.fetch_row
            return row[0]
          end
          convert_items = TaobaoAPI.get_with(:method=>'taobao.taobaoke.items.convert',
                                   :fields=>'iid,num_iid,click_url,commission,commission_rate,shop_click_url,seller_credit_score',
                                   :num_iids=>num_ids,
                                   :nick=>'kqy929')
          if convert_items['error_response']
            puts convert_items['error_response']
            return nil
          elsif  convert_items['taobaoke_items_convert_response']
                ah = {}
                c_items = convert_items['taobaoke_items_convert_response']['taobaoke_items']['taobaoke_item'] unless convert_items['taobaoke_items_convert_response']['taobaoke_items'].nil?
                c_items.each do |ci|
                  if ci.class =='hash'
                      ci['table'] ='taoke_items'
                      escape(ci['title'])
                      ci['created_at']=TaobaoAPI.timestamp
                      ci['updated_at']=TaobaoAPI.timestamp
                      ci['status']=0
                      dao.query(dao.build_sql(ci))
                      taokeid = dao.query("select @@IDENTITY").fetch_row[0]
                      return taokeid
                   else
                      ah[ci[0].to_s]=ci[1].to_s
                  end
                end
                if ah.keys.length>0
                  ah['table'] ='taoke_items'
                  ah['created_at']=TaobaoAPI.timestamp
                  ah['updated_at']=TaobaoAPI.timestamp
                  ah['status']=0
                  dao.query(dao.build_sql(ah))
                  taokeid = dao.query("select @@IDENTITY").fetch_row[0]
                  return taokeid
                end
          end#elseif
        rescue Exception => e
          raise e
        end    
  end
 
 db_config1 = {"host" => '118.126.2.138', 'encoding' => 'utf8', 'username' => 'root', 'password' => 'admin', 'database' => 'tao_hidoudou'}
 tao_dao = DBHelp::DBHelp.out_initialize(db_config1)
 rs = tao_dao.query("select id,u_id,nick,num_iid from tao_items where status>0 and taobaoke_id is null order by id desc")
 rs.each do |row|
    tbk = get_taobaoke_detail(tao_dao,row[2],row[3])
    unless tbk.nil?
        sleep 60
        tao_dao.query("update tao_items set taobaoke_id=#{tbk} where id=#{row[0]}") 
    end
    
     
 end